var designClass = "design_class", hideClass = "hide_class", browseClass = "browse_class", addClass = "add_class", editClass = "edit_class";
var upWindow = window.parent.frames["zwIframe"];

function fy_dialog_close() {
//	window.parent.$(".mask").remove();
//	window.parent.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");
	window.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");

}

function getUpFields(name) {
	return upWindow.$("[validate*='name:\"" + name + "\"']");
}
function getUpFieldsByFieldval(name) {
	return upWindow.$("[fieldval*='displayName:\"" + name + "\"']");
}
function getUpAccountFieldValue(name) {
	var field = getUpFields(name).eq(0);
	return {
		displayValue : field.is("span") ? field.text() : field.val(),
		value : eval("(" + field.parent("span").attr("fieldVal") + ")").value
	};
}

function getUpFieldValueByName(name, index) {
	return getUpFieldValue(getUpFieldsByFieldval(name).eq(index ? index : 0));
}

function getUpFieldValue(field) {
	var fieldVal = field.attr("fieldVal");
	var editTag = field.hasClass(editClass);
	var browseTag = field.hasClass(browseClass);
	var addTag = field.hasClass(addClass);
	if (fieldVal != null && typeof (fieldVal) != 'undefined') {
		fieldVal = eval("(" + fieldVal + ")");
	} else {
		return null;
	}
	var obj = new Object();
	obj.displayName = fieldVal.displayName;
	obj.name = fieldVal.name;
	var tag = true;
	switch (fieldVal.inputType) {
	case "text":
	case "textarea":

		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		} else if (addTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		}
		break;
	case "checkbox":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		}
		break;
	case "radio":
		if (editTag) {
			obj.value = field.find(":radio:checked").attr("val4cal");
		} else if (browseTag) {
			obj.value = field.find(":radio:checked").attr("val4cal");
		}
		break;
	case "select":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name + " option:selected")
					.attr("val4cal");
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).attr("val4cal");
		}
		break;
	case "date":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
			if (obj.value != "") {
				obj.value = obj.value + " 00:00";
			}
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "datetime":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "flowdealoption":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		} else if (addTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "lable":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "relationform":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "relation":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "project":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "member":
	case "multimember":
	case "account":
	case "multiaccount":
	case "department":
	case "multidepartment":
	case "post":
	case "multipost":
	case "level":
	case "multilevel":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name + "_txt").val();
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).text();
		}
		break;
	case "attachment":
	case "image":
	case "document":
		if (editTag || browseTag) {
			var attNames = "";
			var tempField = field.find("#" + fieldVal.name);
			var tempFileId = "";
			if (tempField[0].tagName.toLowerCase() == "input") {
				tempFileId = tempField.val();
			} else if (tempField[0].tagName.toLowerCase() == "span") {
				tempFileId = tempField[0].innerHTML;
			}
			var atts = upWindow.getAttBySubreference(tempFileId);
			for ( var j = 0; j < atts.length; j++) {
				attNames += atts[j].filename + ",";
			}
			if (attNames != "") {
				attNames = attNames.substr(0, attNames.length - 1);
			}
			obj.value = attNames;
		}
		break;
	case "outwrite":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "externalwrite-ahead":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "exchangetask":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "querytask":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	default:
		tag = false;
	}
	if (obj.value != undefined) {
		obj.value = obj.value.replace("\r\n", ";");
		obj.value = obj.value.replace("\n", ";");
	}
	return obj;
}
function setUpFieldValue(name, value) {
	upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input").val(
			value);
	upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input")
			.trigger("blur");
}

function setUpFieldValue2(field, value, displayValue, index) {

	try {

		var fieldVal = field.attr("fieldVal");
		var editTag = field.hasClass(editClass);
		var addTag = field.hasClass(addClass);
		value = (value);
		displayValue = displayValue ? (displayValue) : displayValue;
		if (fieldVal != null && typeof (fieldVal) != 'undefined') {
			fieldVal = eval("(" + fieldVal + ")");
		} else {
			return null;
		}
		var tag = true;
		switch (fieldVal.inputType) {
		case "text":
		case "textarea":
			if (editTag) {
				var inField = field.find("#" + fieldVal.name);
				inField.val(value);
				inField.trigger("blur");
			} else if (addTag) {
				var inField = field.find("#" + fieldVal.name);
				inField.val(value);
				inField.trigger("blur");
			}
			break;
		case "checkbox":
			if (editTag) {
				field.find("#" + fieldVal.name).attr("checked", true);
				field.find("#" + fieldVal.name).trigger("click");
			}
			break;
		case "radio":
			if (editTag) {
				field.find(":radio").eq(index).attr("checked", true);
				field.find(":radio").eq(index).trigger("click");
			}
			break;
		case "select":
			if (editTag) {
				var options = field.find("#" + fieldVal.name + " option");
				for ( var k = 0; k < options.length; k++) {
					if (options.eq(k).text() == value)
						options.eq(k).attr("selected", true);
				}
				field.find("#" + fieldVal.name).trigger("change");
			}
			break;
		case "date":
			if (editTag) {
				field.find("#" + fieldVal.name).val(value);
				field.find("#" + fieldVal.name).trigger("blur");
			}
			break;
		case "datetime":
			if (editTag) {
				field.find("#" + fieldVal.name).val(value);
				field.find("#" + fieldVal.name).trigger("blur");
			}
			break;
		case "member":
		case "multimember":
		case "account":
		case "multiaccount":
		case "department":
		case "multidepartment":
		case "post":
		case "multipost":
		case "level":
		case "multilevel":
			if (editTag) {
				alert(editTag);
				field.find("#" + fieldVal.name + "_txt").val(value);
			}
			break;
		}
	} catch (e) {
		// TODO: handle exception
	}
}
function addOrDelRepeat(name, newLength) {
	var fields = getUpFieldsByFieldval(name);
	var oldLength = fields.length;
	var tbody = getUpFieldsByFieldval(name).eq(0).parent();
	while (!tbody.is("tbody")) {
		tbody = tbody.parent();
	}
	for ( var i = 0, length = Math.abs(newLength - oldLength); i < length; i++) {
		if (newLength > oldLength) {
			upWindow.fy_addEmpty(tbody.children().last());
		} else {
			upWindow.fy_delCurrentRepeat(tbody.children().last());
		}
	}
}

var fields = {
	head : {
		req_number : "计划单号",
		req_inv_org_code : "请求部门",
		actual_mfg_org_code : "生产工厂",
		customer_number : "客户号",
		customer_name : "客户名称",
		address : "发运地址",
		req_source_disp : "来源",
		under_tolerance : "允差下限",
		over_tolerance : "允差上限",
		memo : "备注",
		created_user : "制表",
		req_inv_org_name : "计划库存组织",
		mix_sum : "混装合计",// 混箱合计
		sign_sum : "标箱合计"// 标箱合计
	},
	body : {
		line_num : "行号",
		actual_mfg_org_code : "生产工厂",
		item_name : "本厂编号",
		item_desc : "产品名称",
		part_num : "零件号",
		actual_req_date : "计划日期",
		mix_flag : "混箱标识",
		sum_ol_ordered_quantity : "销售订单数量",
		REQ_QUANTITY : "计划单数量",
		sum_OL_RESERVATION_QUANTITY : "成品扣库数量",
		under_tolerance : "行_允差下限",
		over_tolerance : "行_允差上限",
		PLANNING_MAKE_BUY_CODE : "属性",
		MEMO : "备注2"
	}
};

/**
 * 获取TR的上级节点
 */
var getTRParentNode = function(node) {
	if (node && node.tagName && node.tagName.toUpperCase() != "TR") {
		return getTRParentNode(node.parentNode);
	} else {
		return node.parentNode;
	}
};

function query() {
	var number = document.getElementById("number").value;
	//var factory = document.getElementById("factory").value;
	if (!number || number == "") {
		alert("计划单号不能为空");
		return false;
	}
	// if (!factory || factory == "") {
	// 	alert("生产工厂不能为空");
	// 	return false;
	// }

	var inputs = document.getElementsByTagName("input");

	for ( var i = 0; i < inputs.length; i++) {
		inputs[i].disabled = true;
	}
	var xmlhttp = null;
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				text = xmlhttp.responseText;

				if (text == 1) {
					alert("用户未登陆或计划单号不能为空");
				} else if (text == 2) {
					alert("未查找到对应的单据");
				} else if (text == 3) {
					alert("访问ERP数据库异常");
				} else if (text != "") {
					var salesContract = eval("(" + text + ")");

					for ( var fieldKey in fields.head) {
						setUpFieldValue2(
								getUpFieldsByFieldval(fields.head[fieldKey]).eq(0), (salesContract[fieldKey] ? salesContract[fieldKey]
								: ""));
					}
					var lines = eval("([" + salesContract.lines + "])");
					if (lines) {
						var lineSize = lines.length;
						// var trParentNode = getTRParentNode(pdoc
						// .getElementsByName("行号")[0]);
						// while (pdoc.getElementsByName("行号").length > 1) {
						// trParentNode.lastChild.id = 'oper';
						// window.dialogArguments.del();
						// trParentNode.lastChild.id = "";
						// }
						//
						// for ( var i = 1; i < lineSize; i++) {
						// trParentNode.lastChild.id = 'oper';
						// window.dialogArguments.addEmpty();
						// trParentNode.lastChild.id = "";
						// }
						addOrDelRepeat("行号", lineSize);

						for ( var i = 0; i < lineSize; i++) {
							for ( var bodyKey in fields.body) {
								try {
									setUpFieldValue2(
											getUpFieldsByFieldval(
													fields.body[bodyKey]).eq(i),
											(lines[i][bodyKey] ? lines[i][bodyKey]
													: ""));
									// pdoc
									// .getElementsByName(fields.body[bodyKey])[i].value
									// = (lines[i][bodyKey] ? lines[i][bodyKey]
									// : "");
								} catch (e) {
								}
							}
						}
					}
					fy_dialog_close();
					return;
				} else {
					alert("获取数据发生异常");
				}
				for ( var i = 0; i < inputs.length; i++) {
					inputs[i].disabled = false;
				}
			} else {
				alert("连接服务器异常");
			}
		}
	};
	xmlhttp.open("get",
			"../erp2oaController.do?method=queryOrderContract&number="
					+ encodeURIComponent(number) //+ "&factory="+ encodeURIComponent(factory) 
					+ "&temp=" + Math.random(),
			true);
	xmlhttp.send();

	return false;
}
